/*
 * @Author: fhw
 * @Date: 2022-07-31 12:34:59
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-02-04 21:46:28
 * @Description:
 */
/*
 * @Author: fhw
 * @Date: 2022-07-31 12:34:59
 * @LastEditors: fhw
 * @LastEditTime: 2022-07-31 12:43:24
 * @Description:
 */
import { Injectable, UseFilters } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { isEmpty, isNil } from 'ramda'
import { ChatUser } from 'src/chat_user/entities/chat_user.entity'
import { Repository, IsNull } from 'typeorm'
import { HttpExceptionFilter } from '../http-exception.filter'
import { throwHttp } from '../utlis'
import { CommentDto, CommentInfoIdDto, CommentPageDto } from './dto/article_comment.dto'
import { CommentList, CommentResult } from './entities/article_comment.entity'
@Injectable()
export class ArticleCommentService {
  constructor(
    @InjectRepository(CommentList)
    private articleCommentRepository: Repository<CommentList>,
  ) { }
  @UseFilters(new HttpExceptionFilter())
  async getComment(params: CommentPageDto): Promise<CommentResult> {
    try {
      const pageSize = Number(params.pageSize) || 10
      let { pageNum = 0 } = params
      if (pageNum !== 0) {
        pageNum -= 1
      }
      const [data, total] = await this.articleCommentRepository.findAndCount({
        where: {
          articleId: params.articleId as any,
          commentId: IsNull(),
        },
        relations: ['user','replys','replys.toUser', 'replys.user'],
        skip: pageNum * pageSize,
        take: pageSize,
        cache: true,
      })
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum * pageSize + 1,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 评论详情
  @UseFilters(new HttpExceptionFilter())
  async getCommentInfo({ id, content, userId }: CommentInfoIdDto): Promise<CommentList> {
    const where: any = {}
    if (!isNil(content) && !isNil(userId)) {
      where.content = content
      where.userId = userId
    } else {
      where.id = id
    }
    const data = await this.articleCommentRepository.findOne({
      where,
    })
    if (isNil(data) || isEmpty(data)) {
      throwHttp('评论不存在，请确认id是否正确')
    }
    return data
  }
  // 评论
  @UseFilters(new HttpExceptionFilter())
  async comment(params: CommentDto, { user }: { user: ChatUser }) {
    try {
      const { toUserId, commentId } = params
      const comment = new CommentList()
      comment.articleId = params.articleId
      comment.content = params.content
      comment.userId = params.userId
      comment.user = user
      if (!isNil(toUserId) && !isEmpty(toUserId)) {
        comment.toUserId = toUserId
        comment.commentId = commentId
        const commentInfo = await this.getCommentInfo({ id: params.commentId })
        comment.comment = commentInfo
      }
      await this.articleCommentRepository.manager.save(comment)
      return '发表评论成功'
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 点赞
  @UseFilters(new HttpExceptionFilter())
  async updateCommentLikes(params: CommentInfoIdDto) {
    try {
      const comment = await this.getCommentInfo(params)
      const data = await this.articleCommentRepository
        .createQueryBuilder()
        .update('article_comment')
        .set({
          like_num: comment.like_num + 1,
        })
        .where('id = :id', { id: params.id })
        .execute()
      if (data.affected) {
        return '点赞成功'
      }
      throwHttp('点赞失败')
    } catch (error) {
      throwHttp(error.message)
    }
  }
}
